<template>
  <div>
    <!-- 供应商管理 -->
    <!-- 搜索框 -->
    <el-card>
      <el-form :inline="true" class="demo-form-inline">
        <el-form-item>
          <el-input
            placeholder="搜索框可以搜索账号、持有人、供应商名称"
            v-model="pager.keyword"
            style="width: 500px"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="search"
            >搜索</el-button
          >
          <el-button
            type="primary"
            icon="el-icon-circle-plus-outline"
            @click="handleAdd"
            >添加</el-button
          >
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 列表框 -->
    <el-table
      :data="tableData"
      border
      style="width: 100%"
      :header-cell-style="{ textAlign: 'center' }"
      :cell-style="{ textAlign: 'center' }"
    >
      <el-table-column fixed prop="id" label="Id" width="120">
      </el-table-column>
      <el-table-column prop="accountName" label="账号" width="120">
      </el-table-column>
      <el-table-column prop="owner" label="持有人" width="120">
      </el-table-column>
      <el-table-column prop="phone" label="供应商电话" width="120">
      </el-table-column>
      <el-table-column prop="accountPassword" label="供应商密码" width="120">
      </el-table-column>
      <el-table-column prop="supplierName" label="供应商名称" width="120">
      </el-table-column>
      <el-table-column prop="address" label="供应商所在地" width="120">
      </el-table-column>
      <el-table-column prop="storeName" label="店铺名" width="120">
      </el-table-column>
      <el-table-column prop="managementTypes" label="经营类型" width="120">
      </el-table-column>
      <el-table-column prop="brandName" label="品牌" width="120">
      </el-table-column>
      <el-table-column prop="priority" label="优先级" width="120">
      </el-table-column>
      <el-table-column prop="isActived" label="是否启用" width="120">
        <template slot-scope="scope">
          <el-switch
            active-color="#13ce66"
            inactive-color="#ff4949"
            @change="changeSwitchs(scope.$index, scope.row)"
          >
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column prop="createdTime" label="创建时间" width="120">
      </el-table-column>
      <el-table-column fixed="right" label="操作">
        <template slot-scope="scope">
          <el-button
            @click="handleClick(scope.$index, scope.row)"
            type="text"
            size="small"
            icon="el-icon-edit"
            >编辑</el-button
          >
          <el-button
            type="text"
            size="small"
            icon="el-icon-delete"
            @click="handleDelete(scope.$index, scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加状态框 -->
    <el-dialog title="供应商添加" :visible.sync="dialogFormVisible">
      <el-form
        :model="formData"
        ref="elForm"
        :rules="rules"
        :label-position="labelPosition"
      >
        <el-form-item
          label="账号:"
          prop="accountName"
          :label-width="formLabelWidth"
        >
          <el-input clearable v-model="formData.accountName"></el-input>
        </el-form-item>
        <el-form-item
          label="持有人:"
          prop="owner"
          :label-width="formLabelWidth"
        >
          <el-input clearable v-model="formData.owner"></el-input>
        </el-form-item>
        <el-form-item
          label="供应商电话:"
          prop="phone"
          :label-width="formLabelWidth"
        >
          <el-input clearable v-model="formData.phone"></el-input>
        </el-form-item>
        <el-form-item
          label="供应商密码:"
          prop="accountPassword"
          :label-width="formLabelWidth"
        >
          <el-input clearable v-model="formData.accountPassword"></el-input>
        </el-form-item>

        <el-form-item
          label="供应商名称:"
          prop="supplierName"
          :label-width="formLabelWidth"
        >
          <el-input clearable v-model="formData.supplierName"></el-input>
        </el-form-item>
        <el-form-item
          label="店铺名:"
          prop="storeName"
          :label-width="formLabelWidth"
        >
          <el-input clearable v-model="formData.storeName"></el-input>
        </el-form-item>
        <el-form-item
          label="供应商所在地:"
          prop="address"
          :label-width="formLabelWidth"
        >
          <el-input clearable v-model="formData.address"></el-input>
        </el-form-item>
        <el-form-item
          label="经营类型:"
          prop="managementTypes"
          :label-width="formLabelWidth"
        >
          <el-input clearable v-model="formData.managementTypes"></el-input>
        </el-form-item>
        <el-form-item
          label="品牌:"
          prop="brandName"
          :label-width="formLabelWidth"
        >
          <el-input clearable v-model="formData.brandName"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handeleCancel">取 消</el-button>
        <el-button type="primary" @click="handleSave">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 分页组件 -->

    <div class="block">
      <el-pagination
        @size-change="handlePageSizeChange"
        @current-change="handlePageIndexChange"
        :current-page="pager.pageIndex"
        :page-size="pager.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pager.rowsTotal"
        background
      >
      </el-pagination>
    </div>
  </div>
</template>

<script>
import {
  getSupplier,
  addSupplier,
  modSupplier,
  deleSupplier
} from '../../api/supplier'
// import { getList } from '../../api/role'
import formatTime from '../../utils/formatTime'
import getColor from '../../utils/txorbg'

export default {
  data () {
    return {
      tableData: [],
      dialogFormVisible: false,
      formLabelWidth: '120px',
      labelPosition: 'left',
      currentIndex: 0,
      pager: {
        pageIndex: 1,
        pageSize: 10,
        rowsTotal: 30,
        keyword: ''
      },
      formData: {
        id: 0,
        accountName: '',
        owner: '',
        address: '',
        managementTypes: '',
        brandName: '',
        supplierName: '',
        phone: '',
        accountPassword: '',
        storeName: ''
      },
      options: [],
      rules: {
        accountName: [
          {
            required: true,
            message: '账号不能为空！',
            trigger: ['blur']
          }
        ],
        owner: [
          {
            required: true,
            message: '持有人不能为空！',
            trigger: ['blur']
          }
        ],
        address: [
          {
            required: true,
            message: '供应商地址不能为空！',
            trigger: ['blur']
          }
        ]
      }
    }
  },
  mounted () {
    this.fetchData(this.pager)
  },
  methods: {
    // 搜索
    search () {
      this.pager.pageIndex = 1
      // this.pager.password = 10
      this.fetchData(this.pager)
    },
    // 添加
    handleAdd () {
      this.dialogFormVisible = true
      this.formData.id = 0
      this.formData.accountName = ''
      this.formData.owner = ''
      this.formData.address = ''
      this.formData.managementTypes = ''
      this.formData.brandName = ''
      this.formData.supplierName = ''
      this.formData.phone = ''
      this.formData.accountPassword = ''
      this.formData.storeName = ''
      this.formData.introduction = ''
    },
    // switch开关
    async changeSwitchs (index, row) {
      console.log(index, row)
      const res = await modSupplier(row.id, row)
      console.log(res)
      if (res.data.code === 200) {
        this.$message.success('修改成功')
      } else {
        this.$message.error('修改失败')
      }
    },
    // 编辑
    handleClick (index, row) {
      console.log(row)
      this.dialogFormVisible = true
      this.formData.id = row.id
      this.formData.accountName = row.accountName
      this.formData.owner = row.owner
      this.formData.address = row.address
      this.formData.managementTypes = row.managementTypes
      this.formData.brandName = row.brandName
      this.formData.supplierName = row.supplierName
      this.formData.phone = row.phone
      this.formData.accountPassword = row.accountPassword
      this.formData.storeName = row.storeName

      this.currentIndex = index
      console.log(index, row)
    },
    // 删除用户
    async handleDelete (index, row) {
      // 删除时获得当前数组的下标
      this.currentIndex = index
      row.isDeleted = true

      const res = await deleSupplier(row.id, row)
      if (res.data.code === 200) {
        this.$message.success('删除成功')
        // 删除成功后重新拉取页面
        this.fetchData(this.pager)
      } else {
        row.isDeleted = false
        this.$message.error('删除失败')
      }
    },

    // 添加取消
    handeleCancel () {
      this.dialogFormVisible = false
    },
    // 模态框确定(无论是添加还是修改后保存用户信息)
    handleSave () {
      this.$refs.elForm.validate((valid) => {
        if (!valid) return
        // TODO 提交表单

        console.log('没有错误', this.formData)
        // console.log(this.formData)
        // 如果表单中的id为0，则认为是添加用户，反之则为是修改用户
        if (this.formData.id === 0) {
          const us = this.formData
          us.txcolor = 'white'
          us.bgcolor = getColor()

          addSupplier(us)
            .then((data) => {
              console.log(data)
              // 将新添加的数据Push到现有表数据的里面
              if (data.data.code === 200) {
                const supplier = data.data.data.supplier
                supplier.managementTypes = data.data.data.managementTypes
                supplier.createdTime = formatTime(supplier.createdTime)
                this.tableData.push(supplier)
                this.pager.rowsTotal++
                this.dialogFormVisible = false
                this.$message.success(data.data.msg)
              } else {
                this.dialogFormVisible = false
                this.$message.warning(data.data.msg)
              }
            })
            .catch((err) => {
              console.log(err)
            })
        } else {
          modSupplier(this.formData.id, this.formData)
            .then((data) => {
              console.log(data)
              const obj = data.data.data
              // obj.roleName = data.data.data.supplier.roleName;
              obj.createdTime = formatTime(obj.createdTime)
              this.tableData.splice(this.currentIndex, 1, obj)
              this.dialogFormVisible = false
              this.$message.success(data.data.msg)
            })
            .catch((err) => {
              console.log(err)
            })
        }
      })
    },

    // 当页面大小发生改变的时候，重新拉取数据
    handlePageSizeChange (val) {
      console.log(val)
      this.pager.pageSize = val
      this.fetchData(this.pager)
    },

    // 当页面代码发生改变的时候，重新拉取数据
    handlePageIndexChange (val) {
      console.log(val)
      this.pager.pageIndex = val
      this.fetchData(this.pager)
    },

    // 拉取后台数据并且带上分页
    fetchData (pager) {
      getSupplier(pager).then((data) => {
        console.log(data)
        data.data.data.data.forEach((item) => {
          item.createdTime = formatTime(item.createdTime)
        })

        console.log(data.data.data.data)
        this.tableData = data.data.data.data
        const pager = data.data.data.pager
        pager.keyword = this.pager.keyword
        this.pager = pager
      })
    }
  }
}
</script>

<style>
.block {
  text-align: center;
  /* display: flex; */
  margin-top: 15px;
}
</style>
